package com.ganmiao.server.user.interceptor;

import com.alibaba.fastjson.JSON;
import com.ganmiao.annotation.NoAuthorization;
import com.ganmiao.constant.AuthConstants;
import com.ganmiao.exception.DefaultBusinessException;
import com.ganmiao.resp.ResponseCode;
import com.ganmiao.server.sys.vo.SysUserVo;
import com.ganmiao.server.user.context.UserAuthContext;
import com.ganmiao.server.user.vo.MallUserVo;
import com.ganmiao.server.user.vo.UserLonginVo;
import com.ganmiao.utils.JwtUtils;
import com.ganmiao.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author zero.yin
 * @Date 2022/8/7 10:08 PM
 * @Desc
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验是否无需登录
        NoAuthorization annotation = null;
        boolean checkFlag = true;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(NoAuthorization.class);
        } else {
            return true;
        }
        if (Objects.nonNull(annotation)) {
            checkFlag = false;
        }

        //校验登录
        String token = request.getHeader("token");
        log.info("用户token={},checkFlag={}", token, checkFlag);
        if (StringUtils.isEmpty(token)) {
            if (!checkFlag) {
                return true;
            }
            throw new DefaultBusinessException(ResponseCode.TOKEN_EXPIRED_EXCEPTION);
        }
        if (!JwtUtils.checkToken(token)) {
            throw new DefaultBusinessException(ResponseCode.JWT_EXCEPTION);
        }

        //获取登录信息
        UserLonginVo userLonginVo = getLoginInfo(token);
        //登录用户信息放入私有线程
        SysUserVo loginUser = userLonginVo.getLoginUser();
        MallUserVo mallUser = userLonginVo.getMallUser();
//        RiderLoginVo riderUser = userLonginVo.getRiderUser();
        UserAuthContext.init();
        if (Objects.nonNull(loginUser)) {
            UserAuthContext.setLoginUser(loginUser);
            //系统编码放入私有线程
            UserAuthContext.setSysCode(loginUser.getSysCode());
        }
        if (Objects.nonNull(mallUser)) {
            UserAuthContext.setMallUser(mallUser);
        }
//        if (Objects.nonNull(riderUser)) {
//            UserAuthContext.setRiderUser(riderUser);
//        }

        return true;
    }

    private UserLonginVo getLoginInfo(String token) {
        // ① redis取登录用户信息
        String loginInfoStr = redisUtil.get(AuthConstants.USER_LOGIN + ":" + token);
        if (Objects.isNull(loginInfoStr)) {
            throw new DefaultBusinessException(ResponseCode.TOKEN_EXPIRED_EXCEPTION);
        }
        UserLonginVo userLonginVo = JSON.parseObject(loginInfoStr, UserLonginVo.class);
        // ② 更新reids过期时间
        redisUtil.expire(AuthConstants.USER_LOGIN + ":" + token, AuthConstants.EXP_TOKEN_MILLSECOND);

        return userLonginVo;
    }

}
